package com.quantgroup.data.saastest.service.impl;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quantgroup.data.saastest.bean.TenantDbConfigDO;
import com.quantgroup.data.saastest.config.DataSourceUtil;
import com.quantgroup.data.saastest.config.DynamicDataSource;
import com.quantgroup.data.saastest.config.entity.TenantDbData;
import com.quantgroup.data.saastest.mapper.TenantDbConfigMapper;
import com.quantgroup.data.saastest.service.TenantDbConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author yangjinhua
 */
@Slf4j
@Service
public class TenantDbConfigServiceImpl extends ServiceImpl<TenantDbConfigMapper, TenantDbConfigDO> implements TenantDbConfigService {
	@Resource
	DynamicDataSource multiDataSource;

	/**
	 * 加载数据源
	 */
	@Override
	public void loadDataSource(){
		//数据源
		Map<Object, Object> targetDataSources = new LinkedHashMap<>();

		//获取数据源
		List<TenantDbConfigDO> tenantDbConfigList = baseMapper.selectList(new LambdaQueryWrapper<>());
		//转换
		List<TenantDbData> dataSourceList = tenantDbConfigList.stream().map(item -> {
			TenantDbData dbData = new TenantDbData();
			BeanUtils.copyProperties(item, dbData);
			return dbData;
		}).collect(Collectors.toList());

		//拼装数据源
		for (TenantDbData dbData : dataSourceList) {
			DruidDataSource dataSource = new DruidDataSource();
			dataSource.setUrl(DataSourceUtil.getJDBCUrl(dbData.getDbUrl()));
			dataSource.setUsername(dbData.getDbUsername());
			dataSource.setPassword(dbData.getDbPassword());
			dataSource.setValidationQuery("select 1");
			dataSource.setTestOnBorrow(true);
			targetDataSources.put(dbData.getDbKey(), dataSource);
		}
		multiDataSource.setTargetDataSources(targetDataSources);
		multiDataSource.afterPropertiesSet();
	}

}